<template>
  <div class="task-creation-wizard">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-section">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>{{ userType === 'teacher' ? '教学任务' : '学习任务' }}</el-breadcrumb-item>
        <el-breadcrumb-item>创建{{ userType === 'teacher' ? '教学' : '学习' }}任务</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">创建{{ userType === 'teacher' ? '教学' : '学习' }}任务</h1>
    </div>

    <!-- 白色创建区域 -->
    <div class="creation-container">
      <!-- 步骤进度区域 -->
      <div class="steps-section">
        <el-steps :active="currentStep" finish-status="success" align-center>
          <el-step title="填写任务信息" />
          <el-step title="上传试卷" />
        </el-steps>
      </div>

      <!-- 填写区域 -->
      <div class="form-section">
        <!-- 步骤1: 填写任务信息 -->
        <div v-if="currentStep === 0" class="step-content">
          <el-form ref="taskFormRef" :model="taskForm" :rules="taskRules" class="task-form">
            <!-- 教学任务名称 -->
            <div class="form-field">
              <div class="field-label">
                <span class="required-star">*</span>教学任务名称
              </div>
              <el-form-item prop="name" class="field-input">
                <el-input
                  v-model="taskForm.name"
                  placeholder="请输入教学任务名称"
                  maxlength="50"
                  show-word-limit
                  class="form-input"
                />
              </el-form-item>
              <div class="field-tip">支持中英文及下划线，字符数不超过50字</div>
            </div>

            <!-- 学科类型 -->
            <div class="form-field">
              <div class="field-label">
                <span class="required-star">*</span>学科类型
              </div>
              <el-form-item prop="subject" class="field-input">
                <el-select
                  v-model="taskForm.subject"
                  placeholder="请选择"
                  class="form-input"
                  popper-class="custom-subject-dropdown"
                >
                  <el-option label="语文" value="chinese" />
                  <el-option label="数学" value="math" />
                  <el-option label="英语" value="english" />

                  <!-- 自定义学科选项 -->
                  <el-option
                    v-for="customSubject in customSubjects"
                    :key="customSubject"
                    :label="customSubject"
                    :value="customSubject"
                  />

                  <!-- 分隔线 -->
                  <div class="subject-divider"></div>

                  <!-- 自定义输入区域 -->
                  <div class="custom-subject-section" style="display: flex; flex-direction: row; padding: 8px 12px; align-items: center;">
                    <el-input
                      v-model="customSubjectInput"
                      placeholder="请输入学科类型"
                      size="small"
                      class="custom-input"
                      style="flex: 1; margin-left: 10px;"
                      @keyup.enter="addCustomSubject"
                      @click.stop
                    />
                    <el-button
                      type="text"
                      class="add-other-btn"
                      style="margin-left: 8px; padding: 0 8px; color: #409EFF;"
                      @click.stop="addCustomSubject"
                    >
                      + 其他
                    </el-button>
                  </div>
                </el-select>
              </el-form-item>
            </div>

            <!-- 关联学生 -->
            <div class="form-field">
              <div class="field-label">
                <span class="required-star">*</span>关联学生
              </div>
              <el-form-item prop="students" class="field-input">
                <div class="student-selection">
                  <!-- 已选学生标签区域 -->
                  <div class="selected-students-area">
                    <div class="selected-students-tags">
                      <el-tag
                        v-for="studentId in taskForm.students"
                        :key="studentId"
                        closable
                        @close="removeStudent(studentId)"
                        class="student-tag"
                      >
                        {{ getStudentName(studentId) }}
                      </el-tag>
                      <span v-if="taskForm.students.length === 0" class="placeholder-text">请选择</span>
                    </div>
                    <el-icon class="dropdown-icon" @click="toggleStudentDropdown">
                      <ArrowDown />
                    </el-icon>
                  </div>

                  <!-- 学生选择下拉区域 -->
                  <div v-if="showStudentDropdown" class="student-dropdown">
                    <div class="student-selection-content">
                      <!-- 左侧分组列表 -->
                      <div class="group-list">
                        <div
                          v-for="group in studentGroups"
                          :key="group.id"
                          :class="['group-item', { active: selectedGroup === group.id }]"
                          @click="selectGroup(group.id)"
                        >
                          <el-checkbox
                            :model-value="isGroupSelected(group.id)"
                            @change="toggleGroup(group.id)"
                            @click.stop
                          />
                          <span class="group-name">{{ group.name }}</span>
                          <el-icon class="group-arrow">
                            <ArrowRight />
                          </el-icon>
                        </div>
                      </div>

                      <!-- 右侧学生列表 -->
                      <div class="student-list">
                        <div
                          v-for="student in currentGroupStudents"
                          :key="student.id"
                          class="student-item"
                        >
                          <el-checkbox
                            :model-value="taskForm.students.includes(student.id)"
                            @change="toggleStudent(student.id)"
                          />
                          <span class="student-name">{{ student.name }}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </el-form-item>
            </div>

            <!-- 任务时间 -->
            <div class="form-field">
              <div class="field-label">
                <span class="required-star">*</span>任务时间
              </div>
              <el-form-item prop="timeRange" class="field-input">
                <el-date-picker
                  v-model="taskForm.timeRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  class="form-input time-input"
                  style="width: 75% !important;"
                />
              </el-form-item>
            </div>

            <!-- 教学任务描述 -->
            <div class="form-field">
              <div class="field-label">教学任务描述</div>
              <el-form-item class="field-input">
                <el-input
                  v-model="taskForm.description"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入教学任务描述，字符限制500"
                  maxlength="500"
                  show-word-limit
                  class="form-textarea"
                />
              </el-form-item>
            </div>
          </el-form>
        </div>

        <!-- 步骤2: 上传试卷 -->
        <div v-if="currentStep === 1" class="step-content upload-step">
          <!-- 选择上传模式 -->
          <div class="form-field">
            <div class="field-label">
              <span class="required-star">*</span>选择上传模式
            </div>
            <div class="upload-methods">
              <!-- 拍照上传 -->
              <div class="upload-method" :class="{ active: uploadMethod === 'camera' }"
                @click="selectUploadMethod('camera')">
                <div class="method-icon camera-icon">
                  <el-icon size="24">
                    <Camera />
                  </el-icon>
                </div>
                <div class="method-content">
                  <div class="method-title">拍照上传</div>
                  <div class="method-desc">通过拍照上传试卷</div>
                </div>
                <div v-if="uploadMethod === 'camera'" class="selected-indicator"></div>
              </div>

              <!-- 本地文件上传 -->
              <div class="upload-method" :class="{ active: uploadMethod === 'file' }" @click="selectUploadMethod('file')">
                <div class="method-icon file-icon">
                  <el-icon size="24">
                    <Folder />
                  </el-icon>
                </div>
                <div class="method-content">
                  <div class="method-title">本地文件上传</div>
                  <div class="method-desc">支持上传图片或文件</div>
                </div>
                <div v-if="uploadMethod === 'file'" class="selected-indicator"></div>
              </div>
            </div>
          </div>

          <!-- 上传内容区域 -->
          <div v-if="uploadMethod" class="upload-content-area">
            <div class="form-field">
              <div class="field-label">
                <span class="required-star">*</span>上传试卷
              </div>

              <!-- 上传操作区域 -->
              <div class="upload-actions-area">
                <!-- 拍照上传按钮 -->
                <el-button
                  v-if="uploadMethod === 'camera'"
                  type="default"
                  class="upload-action-btn"
                  @click="openCameraCapture"
                >
                  <el-icon><Camera /></el-icon>
                  拍照上传
                </el-button>

                <!-- 文件上传按钮 -->
                <el-upload
                  v-if="uploadMethod === 'file'"
                  class="file-upload-btn"
                  action="#"
                  :multiple="true"
                  :file-list="[]"
                  :before-upload="beforeUpload"
                  :on-success="handleUploadSuccess"
                  :on-change="handleFileChange"
                  :accept="'.jpg,.jpeg,.png,.pdf,.doc,.docx'"
                  :auto-upload="false"
                  :show-file-list="false"
                >
                  <el-button type="default" class="upload-action-btn">
                    <el-icon><Folder /></el-icon>
                    文件上传
                  </el-button>
                </el-upload>
              </div>

              <!-- 媒体预览区域 -->
              <div v-if="allMediaItems.length > 0" class="media-preview-list">
                <div
                  v-for="(item, index) in allMediaItems"
                  :key="item.id"
                  class="media-item-row"
                >
                  <!-- 图片预览展示 (40px*40px) -->
                  <div class="media-thumbnail-40" :class="getFileTypeClass(item)">
                    <img v-if="item.type === 'photo' || item.type === 'image'" :src="item.src" :alt="item.name" />
                    <el-icon v-else class="file-icon-40">
                      <Document />
                    </el-icon>
                  </div>
                  <!-- div容器(flex-direction为column) -->
                  <div class="media-info-column">
                    <!-- 图片名称(超出容器部分省略) -->
                    <div class="media-name-ellipsis" :title="item.name">{{ item.name }}</div>
                    <!-- 图片大小数据 -->
                    <div class="media-size-text">{{ item.size }}</div>
                  </div>
                  <!-- 删除按钮 - 整个容器右上角的灰色"×" -->
                  <button class="remove-badge" @click="removeMediaItem(index)" title="删除">×</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮区域 -->
      <div class="actions-section">
        <div class="actions-buttons">
          <el-button v-if="currentStep > 0" @click="previousStep">上一步</el-button>
          <el-button v-if="currentStep === 0" @click="handleCancel">取消</el-button>
          <el-button v-if="currentStep < 1" type="primary" @click="nextStep" :loading="loading">
            下一步
          </el-button>
          <el-button v-if="currentStep === 1" type="primary" @click="handleSubmit" :loading="loading">
            创建
          </el-button>
        </div>
      </div>
    </div>

    <!-- 摄像头拍照组件 -->
    <CameraCapture
      v-if="showCameraCapture"
      :user-type="userType"
      context="task-creation"
      :task-name="taskForm.name || '教学任务'"
      @back="closeCameraCapture"
      @capture="handleCameraCapture"
      @import="handleCameraImport" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Camera, Folder, UploadFilled, Document, ArrowDown, ArrowRight } from '@element-plus/icons-vue'
import type { FormInstance, FormRules, UploadFile, UploadFiles } from 'element-plus'
import CameraCapture from '@/components/shared/Camera/CameraCapture.vue'
import { taskListStorage, type TaskListData } from '@/utils/taskListDB'

// 接口定义
interface CapturedPhoto {
  id: string
  thumbnail: string
  fullImage: string
  timestamp: number
  processed?: boolean
}

// Props
interface Props {
  userType: 'teacher' | 'student'
}

const props = withDefaults(defineProps<Props>(), {
  userType: 'teacher'
})

// Emits
const emit = defineEmits<{
  cancel: []
  submit: [data: any]
}>()

// 路由相关
const router = useRouter()
const route = useRoute()

// 响应式数据
const currentStep = ref(0)
const loading = ref(false)
const uploadMethod = ref<'camera' | 'file' | ''>('')
const cameraStarted = ref(false)
const capturedPhotos = ref<string[]>([])
const showCameraCapture = ref(false)
const taskFormRef = ref<FormInstance>()
const uploadRef = ref()
const fileList = ref<UploadFile[]>([])

// 编辑模式相关
const editMode = ref<'create' | 'edit' | 'copy'>('create')
const originalTaskId = ref<string>('')

// 表单数据
const taskForm = reactive({
  name: '',
  subject: '',
  customSubjectName: '', // 自定义学科名称
  students: [] as string[],
  timeRange: [] as string[],
  description: ''
})

// 学科相关状态
const customSubjects = ref<string[]>([]) // 自定义学科列表
const customSubjectInput = ref('') // 自定义学科输入值

// 默认学科选项
const defaultSubjects = [
  { label: '语文', value: 'chinese' },
  { label: '数学', value: 'math' },
  { label: '英语', value: 'english' }
]

// 表单验证规则
const taskRules: FormRules = {
  name: [
    { required: true, message: '请输入教学任务名称', trigger: 'blur' },
    { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' },
    {
      pattern: /^[\u4e00-\u9fa5a-zA-Z0-9_]+$/,
      message: '只支持中英文及下划线',
      trigger: 'blur'
    }
  ],
  subject: [
    { required: true, message: '请选择学科类型', trigger: 'change' }
  ],
  students: [
    { required: true, message: '请选择关联学生', trigger: 'change' }
  ],
  timeRange: [
    { required: true, message: '请选择任务时间', trigger: 'change' }
  ]
}

// 学生选择相关状态
const showStudentDropdown = ref(false)
const selectedGroup = ref('all')

// 学生分组数据（模拟数据）
const studentGroups = ref([
  {
    id: 'all',
    name: '全部',
    students: [
      { id: '1', name: '黎芳华' },
      { id: '2', name: '成白' },
      { id: '3', name: '成白' },
      { id: '4', name: '成白' },
      { id: '5', name: '成白' },
      { id: '6', name: '成白' }
    ]
  },
  {
    id: 'grade8',
    name: '八年级冲刺班',
    students: [
      { id: '1', name: '黎芳华' },
      { id: '2', name: '成白' },
      { id: '3', name: '成白' },
      { id: '4', name: '成白' },
      { id: '5', name: '成白' },
      { id: '6', name: '成白' }
    ]
  },
  {
    id: 'course1',
    name: '这里是课程名称',
    students: [
      { id: '7', name: '李明' },
      { id: '8', name: '王红' }
    ]
  },
  {
    id: 'course2',
    name: '这里是课程名称',
    students: [
      { id: '9', name: '张伟' },
      { id: '10', name: '刘丽' }
    ]
  },
  {
    id: 'course3',
    name: '这里是课程名称',
    students: [
      { id: '11', name: '陈强' },
      { id: '12', name: '赵敏' }
    ]
  }
])

// 计算当前分组的学生
const currentGroupStudents = computed(() => {
  const group = studentGroups.value.find(g => g.id === selectedGroup.value)
  return group ? group.students : []
})

// 合并所有媒体项目（拍照 + 文件上传）
const allMediaItems = computed(() => {
  const items: Array<{
    id: string
    type: 'photo' | 'image' | 'file'
    src: string
    name: string
    size: string
    originalIndex: number
    source: 'photo' | 'file'
  }> = []

  // 添加拍照的照片
  capturedPhotos.value.forEach((photo, index) => {
    items.push({
      id: `photo-${index}`,
      type: 'photo',
      src: photo,
      name: generatePhotoName(index),
      size: calculatePhotoSize(photo),
      originalIndex: index,
      source: 'photo'
    })
  })

  // 添加上传的文件
  fileList.value.forEach((file, index) => {
    items.push({
      id: `file-${file.uid}`,
      type: isImageFile(file) ? 'image' : 'file',
      src: isImageFile(file) ? getFilePreview(file) : '',
      name: file.name || '',
      size: formatFileSize(file.size || 0),
      originalIndex: index,
      source: 'file'
    })
  })

  return items
})

// 自定义学科处理函数
const addCustomSubject = () => {
  const trimmedInput = customSubjectInput.value.trim()
  if (!trimmedInput) {
    ElMessage.warning('请输入学科类型')
    return
  }

  // 检查是否已存在
  const allSubjects = [...defaultSubjects.map(s => s.label), ...customSubjects.value]
  if (allSubjects.includes(trimmedInput)) {
    ElMessage.warning('该学科类型已存在')
    return
  }

  // 添加到自定义学科列表
  customSubjects.value.push(trimmedInput)
  // 自动选择新添加的学科
  taskForm.subject = trimmedInput
  // 重置输入状态
  customSubjectInput.value = ''

  ElMessage.success('学科类型添加成功')
}

// 学生选择相关方法
const toggleStudentDropdown = () => {
  showStudentDropdown.value = !showStudentDropdown.value
}

const selectGroup = (groupId: string) => {
  selectedGroup.value = groupId
}

const getStudentName = (studentId: string) => {
  for (const group of studentGroups.value) {
    const student = group.students.find(s => s.id === studentId)
    if (student) return student.name
  }
  return ''
}

const removeStudent = (studentId: string) => {
  const index = taskForm.students.indexOf(studentId)
  if (index > -1) {
    taskForm.students.splice(index, 1)
  }
}

const toggleStudent = (studentId: string) => {
  const index = taskForm.students.indexOf(studentId)
  if (index > -1) {
    taskForm.students.splice(index, 1)
  } else {
    taskForm.students.push(studentId)
  }
}

const isGroupSelected = (groupId: string) => {
  const group = studentGroups.value.find(g => g.id === groupId)
  if (!group) return false
  return group.students.every(student => taskForm.students.includes(student.id))
}

const toggleGroup = (groupId: string) => {
  const group = studentGroups.value.find(g => g.id === groupId)
  if (!group) return

  const allSelected = group.students.every(student => taskForm.students.includes(student.id))

  if (allSelected) {
    // 取消选择该分组的所有学生
    group.students.forEach(student => {
      const index = taskForm.students.indexOf(student.id)
      if (index > -1) {
        taskForm.students.splice(index, 1)
      }
    })
  } else {
    // 选择该分组的所有学生
    group.students.forEach(student => {
      if (!taskForm.students.includes(student.id)) {
        taskForm.students.push(student.id)
      }
    })
  }
}

// 方法
const nextStep = async () => {
  if (currentStep.value === 0) {
    // 验证第一步表单
    if (!taskFormRef.value) return

    try {
      await taskFormRef.value.validate()
      currentStep.value++
    } catch (error) {
      ElMessage.error('请完善必填信息')
    }
  }
}

const previousStep = () => {
  if (currentStep.value > 0) {
    currentStep.value--
  }
}

const selectUploadMethod = (method: 'camera' | 'file') => {
  uploadMethod.value = method
  // 不清空数据，保持已有的照片和文件
  // 用户可以在两种模式间切换，数据会累积在预览区
}



const handleFileChange = (file: UploadFile, files: UploadFiles) => {
  fileList.value = files
}

const removeFile = (file: UploadFile) => {
  const index = fileList.value.findIndex(f => f.uid === file.uid)
  if (index > -1) {
    fileList.value.splice(index, 1)
  }
}

const formatFileSize = (size: number) => {
  if (size < 1024) {
    return size + ' B'
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(1) + ' KB'
  } else {
    return (size / (1024 * 1024)).toFixed(1) + ' MB'
  }
}

const beforeUpload = (file: File) => {
  const isValidType = ['image/jpeg', 'image/png', 'application/pdf'].includes(file.type)
  const isLt10M = file.size / 1024 / 1024 < 10

  if (!isValidType) {
    ElMessage.error('只能上传 JPG/PNG/PDF 格式的文件!')
    return false
  }
  if (!isLt10M) {
    ElMessage.error('上传文件大小不能超过 10MB!')
    return false
  }
  return true
}

const handleUploadSuccess = (response: any, file: UploadFile) => {
  ElMessage.success('文件上传成功')
}

const handleRemove = (file: UploadFile) => {
  ElMessage.info('文件已移除')
}

// 初始化编辑模式
const initEditMode = async () => {
  const mode = route.query.mode as string
  const taskId = route.query.taskId as string

  if (mode && taskId) {
    editMode.value = mode as 'edit' | 'copy'
    originalTaskId.value = taskId

    try {
      await taskListStorage.init()
      const task = await taskListStorage.getTaskById(taskId)
      
      if (task) {
        // 填充表单数据
        taskForm.name = editMode.value === 'copy' ? `${task.title} - 副本` : task.title
        taskForm.subject = task.subject
        taskForm.students = ['1', '2', '3'] // 模拟关联学生ID
        taskForm.timeRange = [task.startTime, task.endTime]
        taskForm.description = task.description
        
        ElMessage.success(editMode.value === 'edit' ? '任务信息已加载' : '任务信息已复制')
      }
    } catch (error) {
      console.error('加载任务失败:', error)
      ElMessage.error('加载任务失败')
    }
  }
}

const handleCancel = async () => {
  try {
    const actionText = editMode.value === 'edit' ? '编辑' : editMode.value === 'copy' ? '复制' : '创建'
    await ElMessageBox.confirm(`确定要取消${actionText}任务吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 返回任务列表页面
    router.push('/teacher/teaching-tasks')
  } catch {
    // 用户取消
  }
}

const openCameraCapture = () => {
  // 不在这里清理数据，让 CameraCapture 自己决定是否清理
  console.log('TaskCreationWizard: 打开摄像头组件')

  showCameraCapture.value = true
}

const closeCameraCapture = () => {
  showCameraCapture.value = false
}

const handleCameraCapture = (photos: CapturedPhoto[]) => {
  // 追加新拍摄的照片到现有照片列表，而不是替换
  const newPhotos = photos.map(photo => photo.fullImage)
  capturedPhotos.value.push(...newPhotos)
  showCameraCapture.value = false
  ElMessage.success(`已拍摄${photos.length}张照片`)
}

const handleCameraImport = () => {
  // 处理从摄像头界面导入文件
  showCameraCapture.value = false
  selectUploadMethod('file')
}

const removePhoto = (index: number) => {
  capturedPhotos.value.splice(index, 1)
  ElMessage.info('照片已删除')
}

// 删除媒体项目（统一处理拍照和文件上传）
const removeMediaItem = (index: number) => {
  const item = allMediaItems.value[index]
  if (item.source === 'photo') {
    // 删除拍照的照片
    capturedPhotos.value.splice(item.originalIndex, 1)
    ElMessage.info('照片已删除')
  } else if (item.source === 'file') {
    // 删除上传的文件
    fileList.value.splice(item.originalIndex, 1)
    ElMessage.info('文件已删除')
  }
}

// 生成照片名称
const generatePhotoName = (index: number) => {
  const now = new Date()
  const dateStr = now.getFullYear().toString() +
                  (now.getMonth() + 1).toString().padStart(2, '0') +
                  now.getDate().toString().padStart(2, '0')
  return `${dateStr}_${(index + 1).toString().padStart(2, '0')}.jpg`
}

// 计算照片大小
const calculatePhotoSize = (photoData: string) => {
  // Base64字符串大小估算
  const base64Length = photoData.length
  const sizeInBytes = (base64Length * 3) / 4
  const sizeInKB = sizeInBytes / 1024
  return `${sizeInKB.toFixed(1)}KB`
}

// 判断是否为图片文件
const isImageFile = (file: UploadFile) => {
  const imageTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp']
  return file.raw && imageTypes.includes(file.raw.type)
}

// 获取文件预览
const getFilePreview = (file: UploadFile) => {
  if (file.raw && isImageFile(file)) {
    return URL.createObjectURL(file.raw)
  }
  return ''
}

// 根据文件类型获取样式类名
const getFileTypeClass = (item: any) => {
  if (item.type === 'photo' || item.type === 'image') {
    return 'file-image'
  }

  const fileName = item.name.toLowerCase()
  if (fileName.endsWith('.pdf')) {
    return 'file-pdf'
  } else if (fileName.endsWith('.doc') || fileName.endsWith('.docx')) {
    return 'file-doc'
  } else if (fileName.endsWith('.jpg') || fileName.endsWith('.jpeg') || fileName.endsWith('.png') || fileName.endsWith('.gif')) {
    return 'file-image'
  } else {
    return 'file-default'
  }
}

const handleSubmit = async () => {
  if (!uploadMethod.value) {
    ElMessage.error('请选择上传方式')
    return
  }

  if (uploadMethod.value === 'camera' && capturedPhotos.value.length === 0) {
    ElMessage.error('请先拍摄照片')
    return
  }

  if (uploadMethod.value === 'file' && fileList.value.length === 0) {
    ElMessage.error('请上传试卷文件')
    return
  }

  // 直接创建任务，不再区分上传模式
  console.log('开始创建任务，媒体项目数量:', allMediaItems.value.length)
  loading.value = true

  try {
    await taskListStorage.init()
    const { photosStorage } = await import('@/utils/photosDB')
    await photosStorage.init()

    // 构建任务数据
    const taskData: TaskListData = {
      id: editMode.value === 'edit' ? originalTaskId.value : `task-${Date.now()}`,
      title: taskForm.name,
      description: taskForm.description || '教师创建的教学任务',
      subject: taskForm.subject,
      studentCount: taskForm.students.length,
      startTime: taskForm.timeRange[0],
      endTime: taskForm.timeRange[1],
      status: 'pending',
      statusList: [
        { type: 'created', label: '创建', completed: true },
        { type: 'pending', label: '待批改', completed: false },
        { type: 'correction', label: '待订正', completed: false }
      ],
      teacherID: 'teacher-001',
      createdAt: editMode.value === 'edit' ? (await taskListStorage.getTaskById(originalTaskId.value))?.createdAt || new Date().toISOString().replace('T', ' ').substring(0, 19) : new Date().toISOString().replace('T', ' ').substring(0, 19),
      updatedAt: new Date().toISOString().replace('T', ' ').substring(0, 19)
    }

    // 保存任务到数据库
    await taskListStorage.saveTask(taskData)
    console.log('任务已保存到数据库:', taskData)

    // 更新照片的taskId，将临时照片关联到新任务
    const allPhotos = await photosStorage.getAllPhotos()
    const tempPhotos = allPhotos.filter(photo => photo.taskId && photo.taskId.startsWith('temp-'))

    for (const photo of tempPhotos) {
      photo.taskId = taskData.id
      await photosStorage.savePhoto(photo)
      console.log('更新照片taskId:', photo.id, '新taskId:', taskData.id)
    }

    console.log('照片taskId已更新:', tempPhotos.length, '张照片')

    const actionText = editMode.value === 'edit' ? '更新' : editMode.value === 'copy' ? '复制创建' : '创建'
    ElMessage.success(`教学任务${actionText}成功`)

    // 跳转到成功页面
    router.push({
      path: '/teacher/teaching-tasks/success',
      query: {
        taskName: taskData.title,
        taskId: taskData.id
      }
    })
  } catch (error) {
    console.error('保存任务失败:', error)
    ElMessage.error('保存失败，请重试')
  } finally {
    loading.value = false
  }
}

// 点击外部关闭下拉框
const handleClickOutside = (event: Event) => {
  const target = event.target as HTMLElement
  const studentSelection = document.querySelector('.student-selection')
  if (studentSelection && !studentSelection.contains(target)) {
    showStudentDropdown.value = false
  }
}

// 组件挂载时初始化
onMounted(() => {
  initEditMode()

  // 检查是否从拍照页面返回，并恢复照片数据
  const hasPhotos = route.query.hasPhotos as string
  const step = route.query.step as string

  if (hasPhotos === 'true' && step === '1') {
    console.log('检测到从拍照页面返回，恢复照片数据')

    // 恢复任务信息
    const taskInfoStr = sessionStorage.getItem('pendingTaskInfo')
    if (taskInfoStr) {
      const taskInfo = JSON.parse(taskInfoStr)
      console.log('恢复任务信息:', taskInfo)

      // 恢复表单数据
      taskForm.name = taskInfo.name
      taskForm.subject = taskInfo.subject
      taskForm.students = taskInfo.students
      taskForm.timeRange = taskInfo.timeRange
      taskForm.description = taskInfo.description
    }

    // 恢复照片数据（优先从 localStorage 读取）
    let photoDataStr = localStorage.getItem('capturedPhotosData')
    if (!photoDataStr) {
      // 如果 localStorage 中没有，尝试从 sessionStorage 读取（兼容性）
      photoDataStr = sessionStorage.getItem('capturedPhotosData')
    }

    if (photoDataStr) {
      const photoData = JSON.parse(photoDataStr)
      console.log('TaskCreationWizard: 恢复照片数据:', photoData.length, '张照片')
      capturedPhotos.value = photoData
      uploadMethod.value = 'camera'
    } else {
      console.log('TaskCreationWizard: 没有找到照片数据')
    }

    // 设置到第二步
    currentStep.value = 1

    // 清理存储数据
    localStorage.removeItem('capturedPhotosData')
    localStorage.removeItem('currentSessionPhotoIds')
    localStorage.removeItem('currentSessionPhotosData')
    sessionStorage.removeItem('capturedPhotosData')
    sessionStorage.removeItem('pendingTaskInfo')
  }

  // 添加点击外部事件监听
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  // 移除事件监听
  document.removeEventListener('click', handleClickOutside)
})
</script>

<style scoped>
.task-creation-wizard {
  min-height: 100vh;
  background: #f7f8fa;
  padding: 24px;
}

/* 面包屑导航 */
.breadcrumb-section {
  margin-bottom: 16px;
}

:deep(.el-breadcrumb__inner) {
  color: #606266;
  font-size: 14px;
}

:deep(.el-breadcrumb__inner.is-link) {
  color: #409EFF;
}

/* 页面标题 */
.page-header {
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

/* 白色创建区域 */
.creation-container {
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

/* 步骤进度区域 */
.steps-section {
  padding: 30px 48px;
}

.custom-subject-section{
  display: flex;
  flex-direction: row;
}

:deep(.el-steps) {
  max-width: 600px;
  margin: 0 auto;
}

:deep(.el-step__title) {
  font-size: 16px;
  font-weight: 500;
}

/* 填写区域 */
.form-section {
  padding: 15px 48px;
  min-height: 500px;
}

.step-content {
  max-width: 800px;
  margin: 0 auto;
}

/* 表单样式 */
.task-form {
  width: 100%;
  padding: 0 24px;
}

/* 表单字段样式 */
.form-field {
  margin-bottom: 32px;
}

.field-label {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
}

.required-star {
  color: #F56C6C;
  margin-right: 4px;
  font-size: 16px;
}

.field-input {
  margin-bottom: 0;
  position: relative;
}

.field-input :deep(.el-form-item__content) {
  margin-left: 0 !important;
}

.field-input :deep(.el-form-item__error) {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  padding-top: 4px;
  margin: 0;
  font-size: 12px;
  line-height: 1.2;
}

.form-input {
  width: 100%;
  height: 48px;
}

.form-input :deep(.el-input__wrapper) {
  border-radius: 6px;
  border: 1px solid #DCDFE6;
  box-shadow: none;
}

.form-input :deep(.el-input__wrapper:hover) {
  border-color: #C0C4CC;
}

.form-input :deep(.el-input__wrapper.is-focus) {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.form-textarea {
  width: 100%;
}

.form-textarea :deep(.el-textarea__inner) {
  border-radius: 6px;
  border: 1px solid #DCDFE6;
  box-shadow: none;
  resize: vertical;
  min-height: 100px;
}

.form-textarea :deep(.el-textarea__inner:hover) {
  border-color: #C0C4CC;
}

.form-textarea :deep(.el-textarea__inner:focus) {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.field-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
  line-height: 1.4;
}

/* 学科选择相关样式 */
:deep(.custom-subject-dropdown) {
  .subject-divider {
    height: 1px;
    background-color: #e4e7ed;
    margin: 8px 0;
  }

  .custom-subject-section {
    padding: 8px 12px;
    display: flex !important;
    flex-direction: row !important;
    align-items: center;
    gap: 0px;
  }

  .custom-input {
    flex: 1 !important;
    margin-left: 10px !important;
  }

  .custom-input .el-input {
    width: 100% !important;
  }

  .add-other-btn {
    color: #409EFF !important;
    padding: 0 8px !important;
    font-size: 14px !important;
    white-space: nowrap !important;
    margin-left: 8px !important;
  }

  .add-other-btn:hover {
    color: #66b1ff !important;
  }
}

/* 任务时间输入框宽度 - 设置为关联学生输入框的四分之三 */
.time-input {
  width: 75% !important;
}

.time-input :deep(.el-date-editor) {
  width: 100% !important;
}

.time-input :deep(.el-range-editor) {
  width: 100% !important;
}

/* 学生选择相关样式 */
.student-selection {
  position: relative;
  width: 100%;
}

.selected-students-area {
  border: 1px solid #DCDFE6;
  border-radius: 6px;
  padding: 6px 12px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  background: white;
  width: 100%;
  box-sizing: border-box;
}

.selected-students-area:hover {
  border-color: #C0C4CC;
}

.selected-students-area.is-focus {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

.selected-students-tags {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  align-items: center;
}

.student-tag {
  background: #f4f4f5;
  border: 1px solid #e9e9eb;
  color: #606266;
  margin-right: 6px;
  margin-bottom: 4px;
}

.student-tag :deep(.el-tag__close) {
  color: #909399;
}

.student-tag :deep(.el-tag__close:hover) {
  background-color: #c0c4cc;
  color: #fff;
}

.placeholder-text {
  color: #c0c4cc;
  font-size: 14px;
}

.dropdown-icon {
  color: #c0c4cc;
  font-size: 14px;
  transition: transform 0.3s;
}

.student-dropdown {
  position: absolute;
  top: 100%;
  left: 0;
  right: 0;
  z-index: 1000;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-top: 4px;
}

.student-selection-content {
  display: flex;
  height: 300px;
}

.group-list {
  width: 200px;
  border-right: 1px solid #e4e7ed;
  overflow-y: auto;
}

.group-item {
  padding: 12px 16px;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  border-bottom: 1px solid #f5f7fa;
}

.group-item:hover {
  background: #f5f7fa;
}

.group-item.active {
  background: #ecf5ff;
  color: #409eff;
}

.group-name {
  flex: 1;
  font-size: 14px;
}

.group-arrow {
  font-size: 12px;
  color: #c0c4cc;
}

.student-list {
  flex: 1;
  padding: 8px;
  overflow-y: auto;
}

.student-item {
  padding: 8px 12px;
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  border-radius: 4px;
}

.student-item:hover {
  background: #f5f7fa;
}

.student-name {
  font-size: 14px;
  color: #606266;
}

/* 第二步上传样式 */
.upload-step {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.upload-content-area{
  width: 72%;
}
.upload-title {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 32px;
  text-align: left;
}

/* 上传方式选择 */
.upload-methods {
  display: flex;
  gap: 16px;
  margin-bottom: 32px;
  justify-content: center;
}

.upload-method {
  flex: none;
  width: 280px;
  padding: 16px 20px;
  border: 1px solid #DCDFE6;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 12px;
  position: relative;
  background: white;
}

.upload-method:hover {
  border-color: #C0C4CC;
}

.upload-method.active {
  border-color: #409EFF;
  background-color: #F0F9FF;
}

.method-icon {
  width: 40px;
  height: 40px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}

.camera-icon {
  background-color: #E8F5E8;
  color: #67C23A;
}

.file-icon {
  background-color: #E6F7FF;
  color: #409EFF;
}

/* 选中状态的蓝色三角形指示器 */
.selected-indicator {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 0;
  height: 0;
  border-left: 10px solid transparent;
  border-top: 10px solid #409EFF;
}

.upload-area-section{
  display: flex;
  width: 72%;
  justify-content: flex-start;
}
/* .selected-indicator::after {
  content: '';
  position: absolute;
  top: -14px;
  right: -1px;
  width: 0;
  height: 0;
  border-left: 6px solid transparent;
  border-top: 6px solid white;
} */

.method-content {
  flex: 1;
}

.method-title {
  margin: 0 0 4px 0;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.method-desc {
  margin: 0;
  font-size: 12px;
  color: #909399;
}

/* 上传区域样式 */
.camera-upload-btn {
  background: #F5F7FA;
  border: 1px solid #DCDFE6;
  color: #606266;
  padding: 8px 16px;
  border-radius: 4px;
}

.camera-upload-btn:hover {
  background: #E6F7FF;
  border-color: #409EFF;
  color: #409EFF;
}

/* 文件上传拖拽区域 */
.upload-dragger {
  width: 100%;
}

.upload-dragger :deep(.el-upload-dragger) {
  width: 100%;
  height: 200px;
  border: 2px dashed #DCDFE6;
  border-radius: 6px;
  background: #FAFAFA;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.upload-dragger :deep(.el-upload-dragger:hover) {
  border-color: #409EFF;
  background: #F0F9FF;
}

.upload-content {
  text-align: center;
}

.upload-icon {
  font-size: 48px;
  color: #C0C4CC;
  margin-bottom: 16px;
}

.upload-text {
  font-size: 16px;
  color: #303133;
  margin-bottom: 8px;
}

.upload-hint {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.upload-area-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 24px;
}

/* 拍照上传区域 */
.camera-upload-area {
  display: flex;
  flex-direction: column;
  align-items: self-start;
  justify-content: center;
  width: 100%;
}

.camera-upload-btn {
  background: #F5F7FA;
  border: 1px solid #DCDFE6;
  color: #606266;
  padding: 8px 16px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.camera-upload-btn:hover {
  background: #E6F7FF;
  border-color: #409EFF;
  color: #409EFF;
}

/* 已拍摄照片展示区域 */
.captured-photos-list {
  width: 100%;
  max-width: 600px;
  margin-top: 16px;
  display: flex;
  flex-direction: row;
  gap: 12px;
}

.photo-item {
  display: flex;
  align-items: center;
  padding: 16px;
  border: 1px solid #E4E7ED;
  border-radius: 8px;
  background: #F8F9FA;
  position: relative;
  transition: all 0.2s ease;
}

.photo-item:hover {
  background: #F0F2F5;
  border-color: #C0C4CC;
}

.photo-thumbnail {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  overflow: hidden;
  margin-right: 16px;
  background: #B91C1C;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.photo-thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.photo-info {
  flex: 1;
  min-width: 0;
}

.photo-name {
  font-size: 16px;
  color: #2C3E50;
  font-weight: 600;
  margin-bottom: 4px;
  word-break: break-all;
  line-height: 1.4;
}

.photo-size {
  font-size: 14px;
  color: #8E9AAF;
  font-weight: 400;
}

.remove-photo-btn {
  margin-left: 12px;
  color: #E74C3C;
  font-size: 14px;
  padding: 4px 8px;
  flex-shrink: 0;
}

.remove-photo-btn:hover {
  color: #C0392B;
  background: rgba(231, 76, 60, 0.1);
}

/* 已上传文件展示区域 */
.uploaded-files-list {
  width: 100%;
  max-width: 600px;
  margin-top: 16px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 文件图标样式 */
.file-icon {
  font-size: 24px;
  color: white;
}

/* 上传操作区域 */
.upload-actions-area {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.upload-action-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 24px;
  border: 1px solid #DCDFE6;
  border-radius: 6px;
  background: white;
  color: #606266;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.upload-action-btn:hover {
  border-color: #409EFF;
  color: #409EFF;
}

.file-upload-btn {
  display: inline-block;
}

/* 媒体预览列表 - 3列网格布局 */
.media-preview-list {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  position: relative;
  gap: 16px 20px;
  width: 100%;
  margin-top: 16px;
}

/* 每一个子元素的布局 - flex-direction为row的外容器 */
.media-item-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  align-content: center;
  gap: 12px;
  padding: 8px;
  border-radius: 6px;
  background: #FFFFFF;
  border: 1px solid #E4E7ED;
  transition: all 0.2s ease;
  position: relative; /* 添加相对定位，作为删除按钮的定位基准 */
}

.media-item-row:hover {
  background: #F0F9FF;
  border-color: #409EFF;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

/* 图片预览展示 (40px*40px) */
.media-thumbnail-40 {
  width: 40px;
  height: 40px;
  border-radius: 6px;
  overflow: hidden; /* 恢复为hidden */
  background: #B91C1C; /* 红色背景，与设计图一致 */
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  border: 1px solid #E4E7ED;
}

.media-thumbnail-40 img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.file-icon-40 {
  font-size: 20px;
  color: #FFFFFF;
}

/* 为不同文件类型设置不同的背景色 */
.media-thumbnail-40.file-pdf {
  background: #E53E3E; /* PDF文件 - 红色 */
}

.media-thumbnail-40.file-doc {
  background: #3182CE; /* Word文档 - 蓝色 */
}

.media-thumbnail-40.file-image {
  background: #38A169; /* 图片文件 - 绿色 */
}

.media-thumbnail-40.file-default {
  background: #B91C1C; /* 默认 - 红色 */
}

/* div容器(flex-direction为column) */
.media-info-column {
  display: flex;
  flex-direction: column;
  flex: 1;
  min-width: 0;
  gap: 2px;
}

/* 图片名称(超出容器部分省略) */
.media-name-ellipsis {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.2;
}

/* 图片大小数据 */
.media-size-text {
  font-size: 12px;
  color: #909399;
  line-height: 1.2;
}

/* 删除角标 - 灰色的"×"在右上角 */
.remove-badge {
  position: absolute;
  top: -6px;
  right: -6px;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: #909399; /* 灰色背景 */
  color: white;
  font-size: 10px;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  border: none;
  cursor: pointer;
  transition: all 0.2s ease;
  z-index: 10;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}

.remove-badge:hover {
  background: #606266; /* 悬停时更深的灰色 */
  transform: scale(1.1);
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}

.empty-media-state {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 12px;
}

.empty-text {
  font-size: 14px;
  color: #909399;
}

/* 原有的媒体预览区域样式保持兼容 */
.media-preview-area {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  margin-top: 16px;
}

/* 统一媒体预览区域中的媒体项目样式 */
.unified-media-preview-area .media-item {
  width: 100%;
  height: 80px;
  display: flex;
  align-items: center;
  padding: 12px;
  border: 1px solid #E4E7ED;
  border-radius: 8px;
  background: #FFFFFF;
  position: relative;
  transition: all 0.2s ease;
}

.unified-media-preview-area .media-item:hover {
  background: #F0F9FF;
  border-color: #409EFF;
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

/* 原有媒体项目样式保持兼容 */
.media-item {
  width: 160px;
  height: 50px;
  display: flex;
  align-items: center;
  padding: 8px;
  border: 1px solid #E4E7ED;
  border-radius: 6px;
  background: #F8F9FA;
  position: relative;
  transition: all 0.2s ease;
}

.media-item:hover {
  background: #F0F2F5;
  border-color: #C0C4CC;
}

/* 统一媒体预览区域的缩略图样式 */
.unified-media-preview-area .media-thumbnail {
  width: 56px;
  height: 56px;
  border-radius: 6px;
  overflow: hidden;
  margin-right: 12px;
  background: #F5F7FA;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
  border: 1px solid #E4E7ED;
}

.unified-media-preview-area .media-thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.unified-media-preview-area .media-thumbnail .file-icon {
  font-size: 24px;
  color: #909399;
}

/* 原有缩略图样式保持兼容 */
.media-thumbnail {
  width: 34px;
  height: 34px;
  border-radius: 4px;
  overflow: hidden;
  margin-right: 8px;
  background: #B91C1C;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.media-thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 统一媒体预览区域的信息样式 */
.unified-media-preview-area .media-info {
  flex: 1;
  min-width: 0;
  overflow: hidden;
}

.unified-media-preview-area .media-name {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.unified-media-preview-area .media-size {
  font-size: 12px;
  color: #909399;
  margin-bottom: 2px;
}

.unified-media-preview-area .media-source {
  font-size: 11px;
  color: #409EFF;
  background: #F0F9FF;
  padding: 2px 6px;
  border-radius: 3px;
  display: inline-block;
}

/* 原有媒体信息样式保持兼容 */
.media-info {
  flex: 1;
  min-width: 0;
  overflow: hidden;
}

.media-name {
  font-size: 12px;
  color: #2C3E50;
  font-weight: 500;
  margin-bottom: 2px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.media-size {
  font-size: 10px;
  color: #8E9AAF;
  font-weight: 400;
}

/* 统一媒体预览区域的删除按钮样式 */
.unified-media-preview-area .remove-media-btn {
  position: absolute;
  top: 8px;
  right: 8px;
  width: 24px;
  height: 24px;
  border-radius: 50%;
  background: #F56C6C;
  color: white;
  font-size: 14px;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  border: none;
  cursor: pointer;
  z-index: 10;
  transition: all 0.2s ease;
  opacity: 0.8;
}

.unified-media-preview-area .remove-media-btn:hover {
  background: #F56C6C;
  opacity: 1;
  transform: scale(1.1);
}

/* 原有删除按钮样式保持兼容 */
.remove-media-btn {
  position: absolute;
  top: -6px;
  right: -6px;
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: #E74C3C;
  color: white;
  font-size: 12px;
  font-weight: bold;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  border: none;
  cursor: pointer;
  z-index: 10;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.remove-media-btn:hover {
  background: #C0392B;
  transform: scale(1.1);
}

/* 拍照上传小区域 */
.camera-small-area {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 30px;
  border: 2px dashed #409EFF;
  border-radius: 12px;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 24px;
}

.camera-small-area:hover {
  border-color: #1890ff;
  background: linear-gradient(135deg, #e6f7ff 0%, #d1f2ff 100%);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.2);
}

.camera-icon-section {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 80px;
  height: 80px;
  background: rgba(64, 158, 255, 0.1);
  border-radius: 50%;
  flex-shrink: 0;
}

.camera-icon {
  color: #409EFF;
}

.camera-text-section {
  flex: 1;
  text-align: left;
}

.camera-text-section h3 {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 8px 0;
}

.camera-text-section p {
  font-size: 14px;
  color: #606266;
  margin: 0;
  line-height: 1.4;
}

/* 已拍摄照片预览 */
.captured-photos {
  margin-top: 32px;
}

.photos-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
  text-align: left;
}

.photos-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 16px;
}

.photo-item {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 8px;
}

.photo-preview {
  position: relative;
  width: 100px;
  height: 130px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.3s;
}

.photo-preview:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.photo-number {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 24px;
  height: 24px;
  background: #409EFF;
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  font-weight: 600;
  z-index: 1;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.photo-content {
  width: 100%;
  height: 100%;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 模拟试卷照片 */
.mock-paper {
  width: 90%;
  height: 90%;
  background: #fff;
  padding: 8px;
  display: flex;
  flex-direction: column;
  border: 1px solid #e4e7ed;
}

.paper-header {
  font-size: 10px;
  font-weight: 600;
  text-align: center;
  margin-bottom: 6px;
  color: #333;
  line-height: 1.2;
}

.paper-lines {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 3px;
  justify-content: flex-start;
  padding-top: 4px;
}

.line {
  height: 1px;
  background: #ddd;
  width: 100%;
}

.remove-photo-btn {
  font-size: 12px;
  padding: 2px 8px;
}

.camera-container {
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  background: #fafafa;
  min-height: 300px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.camera-placeholder {
  padding: 48px;
}

.camera-placeholder-icon {
  color: #c0c4cc;
  margin-bottom: 16px;
}

.camera-placeholder-text {
  font-size: 16px;
  color: #606266;
  margin: 0 0 24px 0;
}

.start-camera-btn {
  min-width: 120px;
}

.camera-preview {
  width: 100%;
  padding: 24px;
}

.preview-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 24px;
}

.preview-placeholder {
  width: 400px;
  height: 300px;
  border: 2px dashed #409EFF;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f0f9ff;
  color: #409EFF;
}

.camera-controls {
  display: flex;
  gap: 16px;
}

.capture-btn {
  min-width: 100px;
}

/* 文件上传区域 */
.file-upload-area {
  max-width: 600px;
  margin: 0 auto;
}

.upload-dragger {
  width: 100%;
}

:deep(.el-upload-dragger) {
  width: 100%;
  height: 200px;
  border: 2px dashed #d9d9d9;
  border-radius: 8px;
  background: #fafafa;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  transition: all 0.3s;
}

:deep(.el-upload-dragger:hover) {
  border-color: #409EFF;
  background: #f0f9ff;
}

:deep(.el-icon--upload) {
  color: #c0c4cc;
  margin-bottom: 16px;
}

:deep(.el-upload__text) {
  font-size: 14px;
  color: #606266;
}

:deep(.el-upload__text em) {
  color: #409EFF;
  font-style: normal;
}

/* 文件列表 */
.file-list {
  margin-top: 24px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.file-list-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
}

.file-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 0;
  border-bottom: 1px solid #e4e7ed;
}

.file-item:last-child {
  border-bottom: none;
}

.file-icon {
  color: #409EFF;
  flex-shrink: 0;
}

.file-name {
  flex: 1;
  font-size: 14px;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-size {
  font-size: 12px;
  color: #909399;
  flex-shrink: 0;
}

.remove-btn {
  flex-shrink: 0;
}

/* 操作按钮区域 */
.actions-section {
  padding: 24px 48px;
  border-top: 1px solid #f0f0f0;
  background: #fafbfc;
}

.actions-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
}

:deep(.el-button) {
  min-width: 100px;
  height: 40px;
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .form-section {
    padding: 32px;
  }

  .steps-section {
    padding: 24px 32px;
  }

  .actions-section {
    padding: 20px 32px;
  }
}

/* 强制样式覆盖 */
.el-date-editor.time-input {
  width: 75% !important;
}

.el-date-editor.time-input.el-range-editor {
  width: 75% !important;
}

.custom-subject-dropdown .custom-subject-section {
  display: flex !important;
  flex-direction: row !important;
  padding: 8px 12px !important;
  align-items: center !important;
}

.custom-subject-dropdown .custom-subject-section .el-input {
  flex: 1 !important;
  margin-left: 10px !important;
}

.custom-subject-dropdown .custom-subject-section .el-button {
  margin-left: 8px !important;
  padding: 0 8px !important;
}

@media (max-width: 768px) {
  .task-creation-wizard {
    padding: 16px;
  }

  .form-section {
    padding: 24px 16px;
  }

  .steps-section {
    padding: 20px 16px;
  }

  .actions-section {
    padding: 16px;
  }

  .upload-methods {
    flex-direction: column;
  }

  .upload-method {
    max-width: none;
  }

  /* 响应式媒体预览区域 */
  .media-preview-list {
    grid-template-columns: 1fr;
    gap: 12px;
  }

  .media-item-row {
    gap: 8px;
    padding: 6px;
  }

  .media-thumbnail-40 {
    width: 32px;
    height: 32px;
  }

  .file-icon-40 {
    font-size: 16px;
  }

  .media-name-ellipsis {
    font-size: 13px;
  }

  .media-size-text {
    font-size: 11px;
  }

  .remove-badge {
    width: 14px;
    height: 14px;
    font-size: 8px;
    top: -4px;
    right: -4px;
  }

  :deep(.el-form-item__label) {
    width: 100px !important;
  }
}

/* 平板响应式设计 */
@media (min-width: 768px) and (max-width: 1024px) {
  .media-preview-list {
    grid-template-columns: repeat(2, 1fr);
    gap: 14px 16px;
  }
}
</style>